import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WatchRecord } from './watchRecord.entity';
import { WatchRecordIc } from '../watchRecordIc/watchRecordIc.entity';
import DataBase from 'src/config/database';
import { Video } from '../video/video.entity';
import { WorkTypeEnum } from '../watchRecordIc/watchRecordIc.enum';
import utils from 'src/common/utils';
import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import {
  RedisKey
} from './watchRecord.setting'
let {
  redisKeyWatchRecord,
  redisKeyWatchRecordIc
} = RedisKey

@Injectable()
export class WatchRecordService {
  constructor(
    @InjectRepository(WatchRecord)
    private repository: Repository<WatchRecord>,
    @InjectRepository(WatchRecordIc)
    private watchRecordIcRepository: Repository<WatchRecordIc>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRedis() private readonly redis: Redis
  ) {}

  findAll(): Promise<WatchRecord[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<WatchRecord> {
    return this.repository.findOne(id);
  }

  findByVideoIdAndWxUser(video_id, wx_user): Promise<WatchRecord> {
    return this.repository.findOne({where:{video_id, wx_user}})
  }

  async remove(id: number): Promise<void> {
    await this.repository.delete(id);
  }

  async create(cats: WatchRecord, work_type?: string, ic_group?: any): Promise<void> {
    try{
      let removeRedis = () => {
        this.redis.srem(redisKeyWatchRecord + cats.wx_user, cats.video_id)
        if(ic_group){
          this.redis.srem(redisKeyWatchRecordIc + cats.wx_user, ic_group)
        }
      }
      if(await this.findByVideoIdAndWxUser(cats.video_id, cats.wx_user)) {
        removeRedis()
        return
      }
      //查询视频所属网红
      let findVideo = await this.videoRepository.findOne({where:{id: cats.video_id}})
      if(!findVideo){
        throw new Error('视频不存在')
      }
      let findItem = await this.repository.findOne({where:{wx_user: cats.wx_user, video_id: cats.video_id}})
      if(!findItem){
        await this.repository.save(cats);
      }
      if(findVideo.ic_group){
        let watchRecordIc = new WatchRecordIc()
        watchRecordIc.wx_user = cats.wx_user
        watchRecordIc.create_time = new Date()
        watchRecordIc.ic_group = findVideo.ic_group
        let where:any = {wx_user: watchRecordIc.wx_user, ic_group: watchRecordIc.ic_group}
        if(work_type){
          watchRecordIc.work_type = utils.getMainWorkType(work_type)
          where.work_type = watchRecordIc.work_type
        }
        let findItemIc = await this.watchRecordIcRepository.findOne({where: where})
        if(!findItemIc){
          await this.watchRecordIcRepository.save(watchRecordIc)
        }
      }
      removeRedis()
    }catch(err) {
      console.log(err, 'watchrecord create')
    }
  }

  /**
   * 批量创建
   * @param wx_user 
   * @param work_type 
   * @param ids 
   * @param ics 
   */
  async create_batch(wx_user: string, work_type: string, ids: [], ics: []){
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      
      let WatchRecordList = []
      ids.map(video_id => {
        let watchRecord = new WatchRecord()
        watchRecord.create_time = new Date()
        watchRecord.video_id = video_id
        watchRecord.wx_user = wx_user
        WatchRecordList.push(watchRecord)
      })
      let watchRecordIcList = []
      ics.map(ic_group => {
        let watchRecordIc = new WatchRecordIc()
        watchRecordIc.create_time = new Date()
        watchRecordIc.ic_group = ic_group
        watchRecordIc.work_type = utils.getMainWorkType(work_type)
        watchRecordIc.wx_user = wx_user
        watchRecordIcList.push(watchRecordIc)
      })
      if(WatchRecordList.length > 0){
        await this.repository.createQueryBuilder(null, queryRunner).insert().into(WatchRecord).values(WatchRecordList).execute()
      }
      if(watchRecordIcList.length > 0){
        await this.watchRecordIcRepository.createQueryBuilder(null, queryRunner).insert().into(WatchRecordIc).values(watchRecordIcList).execute()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
